package com.inspinia.upms.client.listener;

import com.inspinia.base.common.model.BaseConstants;
import com.inspinia.base.common.model.Status;
import com.inspinia.base.util.DateUtil;
import com.inspinia.config.common.config.SystemConfig;
import com.inspinia.upms.common.model.app.App;
import com.inspinia.upms.rpc.api.ApplicationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.Date;
import java.util.Objects;

/**
 * 系统启动监听器
 * @author veblen
 */
@WebListener
public class SystemRegistryListener implements ServletContextListener{

    protected Logger log = LoggerFactory.getLogger(this.getClass());

    private String ip = SystemConfig.ip;

    private int port = SystemConfig.port;

    private final String sysName = SystemConfig.systemIndexTitleName;

    @Autowired
    private ApplicationService appService;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,sce.getServletContext());
        //系统启动完成，注册系统服务（后续可改成通信协议注册，目前注册至同库）
        App appByName = appService.findAppByName(sysName);

        App app = new App();
        app.setName(sysName);
        app.setIp(ip);
        app.setPort(port);

        if (Objects.isNull(appByName)){
            appService.insert(app);
        }
        log.info("{}已经启动并已注册,启动时间{}",sysName,DateUtil.formatDate(new Date(),BaseConstants.DATE_TIME_PATTERN));
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
       App app = appService.findAppByName(sysName);
        if (Objects.nonNull(app)){
            app.setStatus(Status.disabled);
            appService.update(app);
        }
    }
}
